package gui.toolpanels;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import utils.Utils;

public class JobsPanel extends JPanel {
	public JTable table;
	Vector<Vector<String>> rows;
	Vector<String> cols;
	DefaultTableModel tabModel;
	JScrollPane scrollPane;

	public JobsPanel() {
		super();
		setLayout(new GridLayout(1, 0));
		rows = new Vector<Vector<String>>();
		cols = new Vector<String>();
		cols.add("Jobname");
		cols.add("File");
		cols.add("Status");
		cols.add("Submit time");
		cols.add("Run time");
		cols.add("Command");
		table = new JTable(rows, cols);
		
		table.addMouseListener( new MouseAdapter()
		{
			public void mouseClicked( MouseEvent e )
			{
				if(e.isPopupTrigger())
				{
					Utils.out("popup trigger");
				}
				// Left mouse click
				if ( SwingUtilities.isLeftMouseButton( e ) )
				{
					// Do something
				}
				// Right mouse click
				else if ( SwingUtilities.isRightMouseButton( e ) )
				{
					// get the coordinates of the mouse click
					Point p = e.getPoint();
		 
					// get the row index that contains that coordinate
					int rowNumber = table.rowAtPoint( p );
		 
					// Get the ListSelectionModel of the JTable
					ListSelectionModel model = table.getSelectionModel();
		 
					// set the selected interval of rows. Using the "rowNumber"
					// variable for the beginning and end selects only that one row.
					model.setSelectionInterval( rowNumber, rowNumber );
				}
			}
		});
		tabModel = new DefaultTableModel();
		tabModel.setDataVector(rows, cols);

		table = new JTable(tabModel);
		scrollPane = new JScrollPane(table);// ScrollPane

		// table.getModel().addTableModelListener(this);

		scrollPane
				.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		setPreferredSize(new Dimension(10, 100));
		scrollPane.setPreferredSize(new Dimension(10, 100));
		add(scrollPane);
	}

	public void addRow(Vector<String> data) {
		rows.addElement(data);
		table.addNotify();
		table.revalidate();
	}

	public void updateStatus(String jobname, String status) {
		for (int i = 0; i < rows.size(); i++) {
			if (rows.get(i).get(0).equals(jobname)) {
				rows.get(i).set(2, status);
				table.addNotify();
				break;
			}
		}
	}

	public void deleteAllTerminated() {
		for (int i = 0; i < rows.size(); i++) {
			if (table.getValueAt(i, 2).toString().equals("Terminated")) {
				rows.removeElementAt(i);
				table.addNotify();
				table.revalidate();
			}
		}

	}
}
